package com.ethannhu.todaynews.component.articledetail

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.RecyclerView
import com.ethannhu.repository.DefaultNetworkRepository
import com.ethannhu.todaynews.R
import com.ethannhu.todaynews.component.comment.Comment
import com.ethannhu.todaynews.component.content.Content
import com.ethannhu.todaynews.entity.response.Meta
import com.ethannhu.todaynews.entity.response.onSuccess
import com.ethannhu.todaynews.model.BaseViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import org.apache.commons.lang3.StringUtils

/**
 * 文章详情界面 ViewModel，Activity就可以只处理 UI相关的东西了
 */
class ArticleDetailViewModel(private val id: String) : BaseViewModel() {
    private val _data = MutableSharedFlow<Content>()
    val data: Flow<Content> = _data

    private val _comments = MutableSharedFlow<Meta<Comment>>()
    val comments: Flow<Meta<Comment>> = _comments

    lateinit var content: Content


    fun loadData(lastId: String? = null) {
        viewModelScope.launch(coroutineExceptionHandler) {
            //这个categoryId服务端其实没用到，只是示范
            DefaultNetworkRepository.contentDetail(id)
                .onSuccess(viewModel) {
                    content = it!!
                    _data.emit(it) //数据变更了，另一边的 Activity和 Fragment 都会收到通知
                }
        }
        loadMoreComment()
    }

    private fun loadMoreComment() {
        viewModelScope.launch(coroutineExceptionHandler) {
            //这个categoryId服务端其实没用到，只是示范
            DefaultNetworkRepository.comments(articleId = id)
                .onSuccess(viewModel) {
                    _comments.emit(it)//数据变更了，另一边的 Activity和 Fragment 都会收到通知
                }
        }
    }

    fun loadReplyComment(data: Comment) {
        TODO("Not yet implemented")
    }


}